<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .box1 {
        width: 100px;
        height: 100px;
        background-color: cyan;
        position: absolute;
        left: 0;
      }
      .box2 {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 50%;
      }
    </style>
  </head>
  <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
      var boxEle1 = document.querySelector(".box1");
      var boxEle2 = document.querySelector(".box2");
      var num = 1;
      boxEle1.onclick = function () {
        //盒子点击的时候
        // console.log("点击了");
        var timer = setInterval(function () {
          //创建一个计时器
          var leftNum = parseInt(getComputedStyle(boxEle1)["left"]);
          //找到box1的left值
          leftNum += 10;
          //left值每次加,让box前进
          // console.log(leftNum);
          boxEle1.style.left = leftNum + "px";

          if (isCrash(boxEle1, boxEle2)) {
            //调用函数 如果碰撞了
            clearInterval(timer); //停止计时器
            var timer2 = setInterval(function () {
              //再创建一个让box倒退的计时器
              leftNum -= 10;
              boxEle1.style.left = leftNum + "px";
              if (leftNum <= 0) {
                //如果左边的值小于等于0了也就是说box回到了原点  结束计时器
                clearInterval(timer2);
              }
            }, 20);
          }
        }, 20);
      };

      function isCrash(boxEle1, boxEle2) {
        //检测box1和box2在x轴上是否碰撞了
        var minAx = boxEle1.offsetLeft;
        var maxAx = boxEle1.offsetLeft + boxEle1.offsetWidth;
        var minAy = boxEle1.offsetTop;
        var maxAy = boxEle1.offsetTop + boxEle1.offsetHeight;
        var minBx = boxEle2.offsetLeft;
        var maxBx = boxEle2.offsetLeft + boxEle2.offsetWidth;
        var minBy = boxEle2.offsetTop;
        var maxBy = boxEle2.offsetTop + boxEle2.offsetHeight;
        if (
          maxAx >= minBx &&
          minAx <= maxBx &&
          maxAy >= minBy &&
          minAy <= maxBy
        ) {
          // console.log("碰上了");
          return true;
        } else {
          return false;
        }
      }
    </script>
  </body>
</html>
